<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="layout" content="bocMain"/>
    <title>进件作业系统</title>
</head>

<body>
<header class="header-title">面签合影</header>

<div>
    <input type="hidden" id="token">

    <div class="photoFrame" id="Positive">
        <div class="photo-item ">
            <img src="" alt="" class="imgUrl" id="fileImg">
            <input class="weui-input" type="file" name="file" accept="image/*" capture="camera" id="file">

            <div class="input-box">
                <asset:image src="/boc/photo.png" alt=""/>
                <h5>点击拍摄/上传人像面</h5>
            </div>
        </div>
    </div>

    <div class="face-info">
        <p style="text-align: center">地点：<span id="addressText"></span></p>

        <p style="text-align: center">时间：${new Date().format("yyyy-MM-dd HH:mm:ss")}</p>
    </div>

    <g:form action="visaInterviewStep1Save" class="myForm">
        <input type="hidden" id="id" name="id" value="${this?.opportunity?.id}">
        <input type="hidden" id="fileUrl" name="fileUrl">
        <input type="hidden" id="latitude" name="latitude" value="0">
        <input type="hidden" id="longitude" name="longitude" value="0">
        <input type="hidden" id="address" name="address">
    </g:form>
    <input type="hidden" value="" id="locationData">

    <div class="bigBtn">
        <button class="weui-btn weui-btn_primary" id="submit" type="submit">下一步</button>
    </div>
</div>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.7&key=309fec051f4a8306ea2d8f5710c7c7c2&plugin=AMap.Geolocation,AMap.Geocoder"></script>


<script>

    $(function () {

        getLocation();

        function getLocation() {
            var lnglat;
            var map = new AMap.Map('container', {
                resizeEnable: true
            });

            map.plugin('AMap.Geolocation',function () {
                var geolocation = new AMap.Geolocation({
                    // 是否使用高精度定位，默认：true
                    enableHighAccuracy: true,
                    // 设置定位超时时间，默认：无穷大
                    timeout: 10000,
                    // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                    buttonOffset: new AMap.Pixel(10, 20),
                    //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    zoomToAccuracy: true,
                    //  定位按钮的排放位置,  RB表示右下
                    buttonPosition: 'RB'
                })

                geolocation.getCurrentPosition()
                AMap.event.addListener(geolocation, 'complete', onComplete)
                AMap.event.addListener(geolocation, 'error', onError)

                function onComplete(data) {
                    // data是具体的定位信息
                    var locationData = {
                        longitude: data.position.lng,
                        latitude: data.position.lat
                    };
                    $("#locationData").val(locationData.longitude + "," + locationData.latitude);
                    AMap.plugin('AMap.Geocoder', function () {
                        var geocoder = new AMap.Geocoder();
                        lnglat = $("#locationData").val().split(',');
                        geocoder.getAddress(lnglat, function (status, result) {
                            if (status === 'complete' && result.regeocode) {
                                var address = result.regeocode.formattedAddress;
                                $("#addressText").text(address);
                            } else {
                                alert(result.message);
//                                helpMessage(result.message);
                            }

                        })
                    })

                }

                function onError(result) {
                    // 定位出错
                    alert(result.message);
                }
            })


        }

        function helpMessage(message) {
            $(".helpMsg").text(message).fadeIn(200);
            setTimeout(function () {
                $(".helpMsg").fadeOut(200);
            }, 2000);
        }

        function getUploadToken() {
            var token = ""
            $.ajax({
                type: "POST",
                url: "/attachments/getUploadToken2",
                async: false,
                success: function (data) {
                    if (data.status == "success") {
                        token = data.token;
                        console.log("getUploadToken success.");
                    }
                },
            });
            return token
        }

        function getRandom(length) {
            var str = Math.random().toString(36).substr(2);
            if (str.length >= length) {
                return str.substr(0, length);
            }
            str += getRandom(length - str.length);
            return str;
        }

        function getKey() {
            var timestamp = (new Date()).valueOf();
            return timestamp + '.jpg'
        }

        $("#submit").click(
            function () {
                var fileUrl = $("#fileUrl").val();
                if (fileUrl == "" || fileUrl == undefined) {
                    helpMessage("请拍摄面签合影");
                    return
                }
                $(".myForm").submit();
            }
        )

        var Qiniu_upload = function (f, token, key, name) {
            var Qiniu_UploadUrl = "https://upload-z1.qiniup.com";
            var xhr = new XMLHttpRequest();
            xhr.open('POST', Qiniu_UploadUrl, true);
            var formData = new FormData();
            formData.append('key', key);
            formData.append('token', token);
            formData.append('file', f);
            xhr.onreadystatechange = function (response) {
                if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
                    var blkRet = JSON.parse(xhr.responseText);
                    console.log(blkRet);
                    $("#fileUrl").val(blkRet.key);
                    $("#fileImg").attr("src", "https://quickloanfs.cindata.cn/" + blkRet.key);
                } else if (xhr.status != 200 && xhr.responseText) {
                    var blkRet = JSON.parse(xhr.responseText);
                    console.log(blkRet);
                }
            };
            xhr.send(formData);
        };

        $('#file').change(function () {
            var files = $("#file")[0];
            for (var i = 0; i < files.files.length; i++) {
                var file = files.files[i];
                if (file.size > 1024 * 1024 * 5 + 100) {
                    helpMessage("图片大于5M，请修改后上传");
                    return;
                }
            }
            var token = getUploadToken()
            var key = getRandom(28) + file.name.substr(file.name.lastIndexOf('.'))
            var f = $("#file")[0].files[0]
            Qiniu_upload(f, token, key)
        });

        var message = '${flash.message}';
        if (message) {
            $(".helpMsg").text(message).fadeIn(200);
            setTimeout(function () {
                $(".helpMsg").fadeOut(200);
            }, 2000);
        }
    });
</script>

</body>
</html>